<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="custom-image" content="https://totemlife.cn/apps/public/trial-home-cover.jpg">
    <title>试验管理</title>
    <link href="/apps/css/bootstrap.min.css" rel="stylesheet">
    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
</head>
<body>
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col">
                <h2>
                    <a href="/apps/trial" class="text-decoration-none">临床研究支持</a>
                    <i class="bi bi-chevron-right"></i>
                    试验管理
                </h2>
            </div>
            <div class="col-auto">
                <button type="button" class="btn btn-primary" onclick="showTrialModal()">
                    创建试验
                </button>
            </div>
        </div>

        <div class="row row-cols-1 row-cols-md-2 g-4">
            {{#each trials}}
            <div class="col">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">{{trial_name}}</h5>
                        <p class="card-text"><strong>试验代码:</strong> {{trial_code}}</p>
                        <p class="card-text"><strong>负责人:</strong> {{principal_name}}</p>
                        <p class="card-text"><strong>开始日期:</strong> {{start_date}}</p>
                        <p class="card-text"><strong>结束日期:</strong> {{end_date}}</p>
                        <p class="card-text"><strong>状态:</strong> <span class="badge bg-{{#if (eq trial_status 0)}}warning{{else if (eq trial_status 1)}}primary{{else if (eq trial_status 2)}}success{{else}}danger{{/if}}">{{trial_status_text}}</span></p>
                        <p class="card-text"><strong>招募状态:</strong> <span class="badge bg-{{#if (eq recruit_status 0)}}secondary{{else if (eq recruit_status 1)}}info{{else if (eq recruit_status 2)}}primary{{else}}dark{{/if}}">{{recruit_status_text}}</span></p>
                    </div>
                    <div class="card-footer">
                        {{#if (or (eq ../userId 100) (eq ../userId 1) ) }}
                        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="showTrialModal({{id}})">编辑试验</button>
                        {{/if}}
                        <a href="/apps/trial/admin/trials/{{id}}/subjects" class="btn btn-sm btn-outline-info">受试者管理</a>
                        <a href="/apps/trial/admin/trials/{{id}}/dashboard" class="btn btn-sm btn-outline-primary">试验看板</a>
                    </div>
                </div>
            </div>
            {{/each}}
        </div>
    </div>

    <!-- 创建/编辑试验模态框 -->
    <div class="modal fade" id="trialModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="trialForm" method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">创建试验</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">试验代码</label>
                            <input type="text" class="form-control" name="trial_code" required>
                            <small class="text-muted">默认格式：CT-XXX-YYYYMMDD，创建后不可修改</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">试验名称</label>
                            <input type="text" class="form-control" name="trial_name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">宣传页网址</label>
                            <input type="url" class="form-control" name="promotion_url" placeholder="https://">
                            <small class="text-muted">可选，填写后试验名称将变为可点击链接</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">试验状态</label>
                            <select class="form-select" name="trial_status">
                                <option value="0">准备中</option>
                                <option value="1">进行中</option>
                                <option value="2">已完成</option>
                                <option value="3">已终止</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">招募状态</label>
                            <select class="form-select" name="recruit_status">
                                <option value="0">未开放报名</option>
                                <option value="1">已开放报名</option>
                                <option value="2">招募进行中</option>
                                <option value="3">招募已结束</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">试验描述</label>
                            <textarea class="form-control" name="description" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">开始日期</label>
                            <input type="date" class="form-control" name="start_date" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">结束日期</label>
                            <input type="date" class="form-control" name="end_date">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">报名参加须知</label>
                            <textarea class="form-control" name="apply_tip" rows="5"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">登记入组须知</label>
                            <textarea class="form-control" name="entry_tip" rows="5"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">等待分组须知</label>
                            <textarea class="form-control" name="confirm_tip" rows="5"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">在组试验须知</label>
                            <textarea class="form-control" name="track_tip" rows="5"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">分组提示模板</label>
                            <textarea class="form-control" name="group_info_template" rows="5"></textarea>
                            <div class="form-text">
                                支持HTML和以下变量：<br>
                                {{groupNo}} - 入组编号<br>
                                {{groupType}} - 试验组/对照组
                            </div>
                        </div>
                        <!-- 分组管理配置 -->
                        <div class="mb-3">
                            <label class="form-label">分组管理配置</label>
                            <div id="group-config-container">
                                <div class="card mb-3">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <span>分组配置</span>
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="addGroupConfig()">
                                            <i class="fas fa-plus"></i> 添加分组
                                        </button>
                                    </div>
                                    <div class="card-body">
                                        <div id="group-configs-list">
                                            <!-- 分组配置项会在这里动态生成 -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="group_config" id="group-config-input">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">退出/完成须知</label>
                            <textarea class="form-control" name="exit_tip" rows="5"></textarea>
                            <small class="text-muted">支持HTML格式</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 将所有JS文件移到这里，并添加defer属性 -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js" defer></script>
    <script src="/apps/js/wx-client-dom.js" defer></script>

    <script>
        const trialModal = new bootstrap.Modal(document.getElementById('trialModal'));
        const trialForm = document.getElementById('trialForm');
        const modalTitle = document.getElementById('modalTitle');
        let groupConfigs = []; // 存储分组配置

        async function showTrialModal(trialId = null) {
            // 重置表单
            trialForm.reset();
            // 重置分组配置
            groupConfigs = [];
            document.getElementById('group-configs-list').innerHTML = '';

            if (trialId) {
                // 编辑模式
                modalTitle.textContent = '编辑试验';
                trialForm.action = `/apps/trial/admin/trials/${trialId}`;

                // 获取试验详情
                try {
                    const response = await fetch(`/apps/trial/admin/trials/${trialId}`);
                    const data = await response.json();

                    if (data.success) {
                        // 填充表单
                        const trial = data.trial;
                        trialForm.querySelector('[name="trial_code"]').value = trial.trial_code;
                        trialForm.querySelector('[name="trial_code"]').readOnly = true;  // 编辑时不可修改
                        trialForm.querySelector('[name="trial_name"]').value = trial.trial_name;
                        trialForm.querySelector('[name="promotion_url"]').value = trial.promotion_url || '';
                        trialForm.querySelector('[name="trial_status"]').value = trial.trial_status;
                        trialForm.querySelector('[name="recruit_status"]').value = trial.recruit_status;
                        trialForm.querySelector('[name="description"]').value = trial.description;
                        trialForm.querySelector('[name="start_date"]').value = trial.start_date;
                        trialForm.querySelector('[name="end_date"]').value = trial.end_date;
                        trialForm.querySelector('[name="apply_tip"]').value = trial.apply_tip;
                        trialForm.querySelector('[name="entry_tip"]').value = trial.entry_tip;
                        trialForm.querySelector('[name="track_tip"]').value = trial.track_tip;
                        trialForm.querySelector('[name="exit_tip"]').value = trial.exit_tip;
                        trialForm.querySelector('[name="confirm_tip"]').value = trial.confirm_tip;
                        trialForm.querySelector('[name="group_info_template"]').value = trial.group_info_template;

                        // 加载分组配置
                        if (trial.group_config) {
                            try {
                                groupConfigs = JSON.parse(trial.group_config);
                                renderGroupConfigs();
                            } catch (e) {
                                console.error('解析分组配置失败:', e);
                                groupConfigs = [];
                            }
                        }
                    } else {
                        alert(data.message || '获取试验信息失败');
                        return;
                    }
                } catch (error) {
                    console.error('获取试验信息失败:', error);
                    alert('获取试验信息失败');
                    return;
                }
            } else {
                // 创建模式
                modalTitle.textContent = '创建试验';
                trialForm.action = '/apps/trial/admin/trials';
                // 生成默认试验代码
                const today = new Date();
                const dateStr = today.getFullYear() +
                    String(today.getMonth() + 1).padStart(2, '0') +
                    String(today.getDate()).padStart(2, '0');
                trialForm.querySelector('[name="trial_code"]').value = `CT-TL-${dateStr}`;
                trialForm.querySelector('[name="trial_code"]').readOnly = false;  // 创建时可修改

                // 添加默认分组配置（试验组和对照组）
                groupConfigs = [
                    {
                        group_type: 1,
                        group_name: "试验组",
                        duration: 90,
                        daily_diary: true,
                        follow_up_dates: [15, 30, 60, 90]
                    },
                    {
                        group_type: 2,
                        group_name: "对照组",
                        duration: 90,
                        daily_diary: true,
                        follow_up_dates: [15, 30, 60, 90]
                    }
                ];
                renderGroupConfigs();
            }

            trialModal.show();
        }

        // 添加分组配置
        function addGroupConfig() {
            const newGroupType = groupConfigs.length + 1;
            groupConfigs.push({
                group_type: newGroupType,
                group_name: newGroupType === 1 ? "试验组" : (newGroupType === 2 ? "对照组" : `分组${newGroupType}`),
                duration: 90,
                daily_diary: true,
                follow_up_dates: [15, 30, 60, 90]
            });
            renderGroupConfigs();
        }

        // 删除分组配置
        function removeGroupConfig(index) {
            if (confirm('确定要删除这个分组配置吗？')) {
                groupConfigs.splice(index, 1);
                renderGroupConfigs();
            }
        }

        // 更新分组配置
        function updateGroupConfig(index, field, value) {
            if (field === 'follow_up_dates') {
                // 处理随访日期输入
                try {
                    value = value.split(',').map(item => parseInt(item.trim())).filter(item => !isNaN(item));
                } catch (e) {
                    console.error('解析随访日期失败:', e);
                    value = [];
                }
            } else if (field === 'daily_diary') {
                value = value === 'true';
            } else if (field === 'duration' || field === 'group_type') {
                value = parseInt(value);
            }

            groupConfigs[index][field] = value;
            updateGroupConfigInput();
        }

        // 渲染分组配置列表
        function renderGroupConfigs() {
            const container = document.getElementById('group-configs-list');
            container.innerHTML = '';

            groupConfigs.forEach((config, index) => {
                const configHtml = `
                    <div class="card mb-3">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <span>分组 ${index + 1}</span>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeGroupConfig(${index})">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="row mb-2">
                                <div class="col-md-6">
                                    <label class="form-label">分组类型</label>
                                    <input type="number" class="form-control" value="${config.group_type}"
                                           onchange="updateGroupConfig(${index}, 'group_type', this.value)">
                                    <small class="text-muted">数字标识，例如1表示试验组</small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">分组名称</label>
                                    <input type="text" class="form-control" value="${config.group_name}"
                                           onchange="updateGroupConfig(${index}, 'group_name', this.value)">
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-6">
                                    <label class="form-label">随访天数</label>
                                    <input type="number" class="form-control" value="${config.duration}"
                                           onchange="updateGroupConfig(${index}, 'duration', this.value)">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">每日打卡</label>
                                    <select class="form-select"
                                            onchange="updateGroupConfig(${index}, 'daily_diary', this.value)">
                                        <option value="true" ${config.daily_diary ? 'selected' : ''}>是</option>
                                        <option value="false" ${!config.daily_diary ? 'selected' : ''}>否</option>
                                    </select>
                                </div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">定期随访日期（逗号分隔）</label>
                                <input type="text" class="form-control" value="${config.follow_up_dates.join(', ')}"
                                       onchange="updateGroupConfig(${index}, 'follow_up_dates', this.value)">
                                <small class="text-muted">从开始日期算起的第几天需要填写随访表，例如：15, 30, 60, 90</small>
                            </div>
                        </div>
                    </div>
                `;

                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = configHtml;
                container.appendChild(tempDiv.firstElementChild);
            });

            updateGroupConfigInput();
        }

        // 更新隐藏输入字段的值
        function updateGroupConfigInput() {
            document.getElementById('group-config-input').value = JSON.stringify(groupConfigs);
        }

        // 表单提交处理
        trialForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const data = {};
            formData.forEach((value, key) => data[key] = value);

            try {
                const response = await fetch(this.action, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                const result = await response.json();

                if (result.success) {
                    // 直接刷新页面
                    window.location.href = '/apps/trial/admin/trials';
                } else {
                    alert(result.message || '保存失败');
                }
            } catch (error) {
                console.error('保存失败:', error);
                alert('保存失败，请重试');
            }
        });

    </script>
</body>
</html>
